"""
系统监控服务
"""
import psutil
import time
from datetime import datetime, timedelta
from typing import Dict, Any, Optional
from sqlalchemy.orm import Session
from sqlalchemy import desc
from models.database import SystemMetrics
from core.database import SessionLocal
from core.logger import get_logger

logger = get_logger(__name__)

# 全局缓存变量
_system_metrics_cache: Optional[Dict[str, Any]] = None
_last_cache_update: Optional[datetime] = None
CACHE_DURATION = 1  # 缓存1秒

class SystemMonitorService:
    """系统监控服务"""
    
    # @staticmethod
    # def get_current_metrics(monitor_interval: int) -> Dict[str, Any]:
    #     """获取当前系统指标"""
    #     try:
    #         # CPU使用率
    #         cpu_percent = psutil.cpu_percent(interval=monitor_interval)
            
    #         # 内存使用情况
    #         memory = psutil.virtual_memory()
    #         memory_percent = memory.percent
    #         memory_used = memory.used // (1024 * 1024)  # MB
    #         memory_total = memory.total // (1024 * 1024)  # MB
            
    #         # 磁盘使用情况
    #         disk = psutil.disk_usage('/')
    #         disk_percent = disk.percent
    #         disk_used = disk.used // (1024 * 1024 * 1024)  # GB
    #         disk_total = disk.total // (1024 * 1024 * 1024)  # GB
            
    #         # 系统负载
    #         load_avg = psutil.getloadavg()[0] if hasattr(psutil, 'getloadavg') else 0.0
            
    #         # 系统运行时间
    #         uptime = time.time() - psutil.boot_time()
            
    #         return {
    #             'cpu_percent': round(cpu_percent, 1),
    #             'memory_percent': round(memory_percent, 1),
    #             'memory_used': memory_used,
    #             'memory_total': memory_total,
    #             'disk_percent': round(disk_percent, 1),
    #             'disk_used': disk_used,
    #             'disk_total': disk_total,
    #             'load_average': round(load_avg, 2),
    #             'uptime': int(uptime),
    #             'timestamp': datetime.now()
    #         }
    #     except Exception as e:
    #         logger.error(f"获取系统指标失败: {e}")
    #         # 返回默认值
    #         return {
    #             'cpu_percent': 0.0,
    #             'memory_percent': 0.0,
    #             'memory_used': 0,
    #             'memory_total': 0,
    #             'disk_percent': 0.0,
    #             'disk_used': 0,
    #             'disk_total': 0,
    #             'load_average': 0.0,
    #             'uptime': 0,
    #             'timestamp': datetime.now()
    #         }
    
    @staticmethod
    def save_metrics_to_db(metrics: Dict[str, Any]) -> None:
        """保存系统指标到数据库"""
        try:
            db = SessionLocal()
            db_metrics = SystemMetrics(
                cpu_percent=metrics['cpu_percent'],
                memory_percent=metrics['memory_percent'],
                memory_used=metrics['memory_used'],
                memory_total=metrics['memory_total'],
                disk_percent=metrics['disk_percent'],
                disk_used=metrics['disk_used'],
                disk_total=metrics['disk_total'],
                load_average=metrics['load_average'],
                uptime=metrics['uptime']
            )
            db.add(db_metrics)
            db.commit()
            db.close()
        except Exception as e:
            logger.error(f"保存系统指标到数据库失败: {e}")
    
    @staticmethod
    def set_cached_metrics(current_metrics_cache: Dict[str, Any]) -> Dict[str, Any]:
        """获取缓存的系统指标"""
        global _system_metrics_cache, _last_cache_update
        if current_metrics_cache:
            _system_metrics_cache = current_metrics_cache
            _last_cache_update = datetime.now()
        return _system_metrics_cache

    @staticmethod
    def get_current_metrics(monitor_interval: int) -> Dict[str, Any]:
        """获取当前系统指标"""
        current_time = datetime.now()
        # 获取新的指标，使用非阻塞方式获取CPU使用率
        metrics = None
        try:
            # 先获取非阻塞的CPU使用率
            cpu_percent = psutil.cpu_percent(interval=monitor_interval)
            
            # 获取其他指标
            memory = psutil.virtual_memory()
            disk = psutil.disk_usage('/')
            load_avg = psutil.getloadavg()[0] if hasattr(psutil, 'getloadavg') else 0.0
            uptime = time.time() - psutil.boot_time()
            
            metrics = {
                'cpu_percent': round(cpu_percent, 1),
                'memory_percent': round(memory.percent, 1),
                'memory_used': memory.used // (1024 * 1024),
                'memory_total': memory.total // (1024 * 1024),
                'disk_percent': round(disk.percent, 1),
                'disk_used': disk.used // (1024 * 1024 * 1024),
                'disk_total': disk.total // (1024 * 1024 * 1024),
                'load_average': round(load_avg, 2),
                'uptime': int(uptime),
                'timestamp': current_time
            }
        except Exception as e:
            logger.error(f"获取系统指标失败: {e}")
            metrics = {
                'cpu_percent': 0.0,
                'memory_percent': 0.0,
                'memory_used': 0,
                'memory_total': 0,
                'disk_percent': 0.0,
                'disk_used': 0,
                'disk_total': 0,
                'load_average': 0.0,
                'uptime': 0,
                'timestamp': current_time
            }
        return metrics

    @staticmethod
    def get_cached_metrics() -> Dict[str, Any]:
        """获取缓存的系统指标"""
        global _system_metrics_cache, _last_cache_update  
        return _system_metrics_cache
    
    @staticmethod
    def get_metrics_history(hours: int = 24) -> list:
        """获取历史系统指标"""
        try:
            db = SessionLocal()
            since_time = datetime.now() - timedelta(hours=hours)
            
            metrics = db.query(SystemMetrics).filter(
                SystemMetrics.timestamp >= since_time
            ).order_by(desc(SystemMetrics.timestamp)).limit(1000).all()
            
            db.close()
            
            return [{
                'cpu_percent': m.cpu_percent,
                'memory_percent': m.memory_percent,
                'disk_percent': m.disk_percent,
                'load_average': m.load_average,
                'timestamp': m.timestamp.isoformat()
            } for m in metrics]
        except Exception as e:
            logger.error(f"获取历史系统指标失败: {e}")
            return []
    
    @staticmethod
    def cleanup_old_metrics(days: int = 7) -> None:
        """清理旧的系统指标数据"""
        try:
            db = SessionLocal()
            cutoff_time = datetime.now() - timedelta(days=days)
            
            deleted = db.query(SystemMetrics).filter(
                SystemMetrics.timestamp < cutoff_time
            ).delete()
            
            db.commit()
            db.close()
            
            logger.info(f"清理了 {deleted} 条旧的系统指标数据")
        except Exception as e:
            logger.error(f"清理旧的系统指标数据失败: {e}")
    
    @staticmethod
    def format_uptime(seconds: int) -> str:
        """格式化运行时间"""
        days = seconds // 86400
        hours = (seconds % 86400) // 3600
        minutes = (seconds % 3600) // 60
        
        if days > 0:
            return f"{days}天 {hours}小时"
        elif hours > 0:
            return f"{hours}小时 {minutes}分钟"
        else:
            return f"{minutes}分钟"
    
    @staticmethod
    def get_system_status() -> str:
        """获取系统状态"""
        try:
            metrics = SystemMonitorService.get_cached_metrics()
            
            # 根据CPU、内存、磁盘使用率判断系统状态
            if metrics['cpu_percent'] > 80 or metrics['memory_percent'] > 80:
                return "繁忙"
            elif metrics['cpu_percent'] > 60 or metrics['memory_percent'] > 60:
                return "正常"
            else:
                return "良好"
        except Exception:
            return "未知"